package com.lgl.scsapi.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局过滤器
 */
@Component
// 定义filterName 和过滤的url
@WebFilter(urlPatterns = "/*")
public class GlobalFilter implements Filter {
    //访问域名
    @Value("${server.domain-name}")
    private String domainName;
    private static String comma = ",";

    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String referer = request.getHeader("Referer"),
        path = request.getServletPath();

        //如果是非法请求
        if(isBadRequest(referer,path)){
            //跳转到错误页面，会自动找到ErrorPageConfig对应的错误页面
            response.sendError(400);
            return;
        }
        chain.doFilter(req, res);
    }
    @Override
    public void destroy() {

    }

    /**
     * 判断是否为非法请求
     * @param referer 请求Header中的Referer
     * @param requestUrl 请求路径
     * @return true:非法请求,false:合法请求
     */
    private boolean isBadRequest(String referer,String requestUrl){
        //html的请求Header中的Referer为空
        if (!StringUtils.hasText(referer)){
            if ("/".equals(requestUrl)){
                return false;
            }
            //如果referer为空，且是html页面的地址，则认为是合法的请求
            requestUrl = requestUrl.split("\\?")[0];
            return !requestUrl.endsWith(".html");
        }
        //获取域名
        referer = referer.split("://")[1];
        referer = referer.split("/")[0];
        referer = referer.split(":")[0];
        referer = referer.replaceAll("www.","");
        domainName += comma;
        referer += comma;
        //如果配置的合法域名（域名有多个，用“,”隔开）中不包含Referer，则是非法请求
        return !domainName.contains(referer);
    }
}